package com.beg.cant.config;


import com.beg.cant.comment.MessageConstant;
import com.beg.cant.comment.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DataAccessException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理器，处理项目中抛出的业务异常
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理 SQL 相关的异常
     * @param ex
     * @return
     */
    @ExceptionHandler
    private Result handleSqlException(DataAccessException ex) {
        log.error("sql执行异常{}",ex.getMessage());
        //### Error updating database.  Cause: java.sql.SQLIntegrityConstraintViolationException: Duplicate entry '张三' for key 'idx_username'
        String message = ex.getMessage();
        if(message.contains("Duplicate entry")){
            String[] split = message.split(" ");
            String username = split[9];
            String msg = username + MessageConstant.ALREADY_EXISTS;
            return Result.error(msg);
        }else{
            return Result.error(MessageConstant.UNKNOWN_ERROR);
        }
    }

    /**
     * 处理其他类型的异常
     * @param ex
     * @return
     */
    @ExceptionHandler
    private Result handleOtherException(Exception ex) {
        log.error("Exception异常全局捕获");
        log.error(ex.getMessage());
        return Result.error(ex.getMessage());
    }
}
